<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="嵌入式开发中的一个基本共识是，不能在中断处理函数中做耗时的工作。中断函数中应该只处理最紧急的工作，剩下的工作应该放到线程模式（执行普通代码的模式）下运行。FreeRTOS提供的延后执行功能，就是针对这种需求设计的。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS-延后执行机制">
<meta property="og:url" content="http://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="嵌入式开发中的一个基本共识是，不能在中断处理函数中做耗时的工作。中断函数中应该只处理最紧急的工作，剩下的工作应该放到线程模式（执行普通代码的模式）下运行。FreeRTOS提供的延后执行功能，就是针对这种需求设计的。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/old-method.png">
<meta property="og:image" content="http://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/button-interrput.png">
<meta property="og:image" content="http://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/deferring-schema.png">
<meta property="article:published_time" content="2022-11-30T16:00:00.000Z">
<meta property="article:modified_time" content="2023-02-02T15:16:54.499Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/old-method.png">


<link rel="canonical" href="http://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/","path":"2022/12/01/FreeRTOS-deferring-work/","title":"FreeRTOS-延后执行机制"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS-延后执行机制 | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8FreeRTOS%E7%9A%84%E5%BB%B6%E5%90%8E%E6%89%A7%E8%A1%8C%E5%8A%9F%E8%83%BD%EF%BC%9A"><span class="nav-number">1.</span> <span class="nav-text">使用FreeRTOS的延后执行功能：</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS-延后执行机制 | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS-延后执行机制
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-12-01 00:00:00" itemprop="dateCreated datePublished" datetime="2022-12-01T00:00:00+08:00">2022-12-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>4.3k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>5 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>

<p>嵌入式开发中的一个基本共识是，不能在中断处理函数中做耗时的工作。中断函数中应该只处理最紧急的工作，剩下的工作应该放到线程模式（执行普通代码的模式）下运行。FreeRTOS提供的<code>延后执行</code>功能，就是针对这种需求设计的。</p>
</center>
<span id="more"></span>

<hr>
<p>中断机制的存在是为了处理一些紧急请求，如外部数据到来，用户按键等，这些请求都是需要立刻处理的。</p>
<p>如串口数据接收中断，如果我们在串口中断处理函数中提取接收到的数据后，进一步执行更复杂的应用数据分析等工作，那么这段时间内，由于一直处于中断上下文中，其它较低优先级的中断以及当前的串口中断再次发生时，就无法得到及时处理（只有当前中断函数退出后，才会执行其它中断处理函数）。甚至，如果处于中断上下文中的时间太长，会导致丢失掉某些中断事件（期间某个中断A 发生了多次，但无法得到处理，由于硬件上中断悬起标记只有一位，只能表示发生了中断，无法得知发生了几次，那么当前中断结束后，只会调用一次中断A的处理函数。），或者丢失掉一些数据（例如，未使用串口的硬件流控机制时，如果串口中断处理函数耗时太久，cpu不能及时将接收到的数据从串口硬件缓存中提取出来，那么连续发送数据时就会存在丢失的情况）。</p>
<p>因此，实际应用中，中断处理函数中只做一些必要的工作，其它耗时操作会延后到退出中断后再执行。 裸机程序通常会使用一个标记，来表明是否发生了某个中断需要处理。如下图所示：<br><img src="/2022/12/01/FreeRTOS-deferring-work/old-method.png"></p>
<p>如此，我们既完成了中断触发后，所需要做的所有工作（紧急的工作中断函数中做，次要的延后到退出中断函数后再做）。同时，由于及时退出了中断处理函数，这样就可以尽最大可能避免影响其它低优先级的中断（无论中断优先级高低，处理中断都比普通代码执行的工作更重要，因此应该尽最大可能避免高优先级中断影响低优先级中断）。</p>
<p>但如上文逻辑程序中，使用 flag 标记的方法并不优雅，也不利于维护。<br>基于RTOS 的实现，一般会单独创建一个任务，用来处理需要延后执行的那些工作。例如在文章<a href="https://fengxun2017.github.io/2022/11/16/FreeRTOS-use-timer/#%E5%91%A8%E6%9C%9F%E5%AE%9A%E6%97%B6%E5%99%A8%E4%BD%BF%E7%94%A8%E6%A0%B7%E4%BE%8B%EF%BC%9A">FreeRTOS-软件定时器的使用，周期定时器的使用一节</a>中。在实现按键处理时，就是单独创建了一个按键处理任务，并让其阻塞在一个信号量上。而当按键按下，进入中断处理程序，做完必要操作后，会设置这个信号量。如此，等中断函数退出后，按键处理任务由于获得了信号量，就会恢复运行并处理剩下的工作。如下图所示：<br><img src="/2022/12/01/FreeRTOS-deferring-work/button-interrput.png"></p>
<p>这种实现方式逻辑上更清晰，并且使代码更具维护性和扩展性。但存在一个弊端，即需要额外创建任务，信号量等资源。对于一些轻量、中量级的延后处理工作来说，单独为它们创建一个任务并使用信号量这些资源，可能“得不偿失”（在内存紧张的处理器上，更为明显）。</p>
<p>因此，FreeRTOS 针对这种使用场景（即一些工作没必要在中断处理函数中做，但为此单独创建一个任务又浪费资源），提供了一个“延后执行”功能。同样是让非必要工作延后执行，但是基于FreeRTOS内核的“延后执行”功能，我们只需要提供一个执行那些延后工作的处理函数即可，内核会自动帮我们调用该函数。这样可以避免需要单独创建一个任务，并使用信号量进行事件同步。</p>
<h4 id="使用FreeRTOS的延后执行功能："><a href="#使用FreeRTOS的延后执行功能：" class="headerlink" title="使用FreeRTOS的延后执行功能："></a>使用FreeRTOS的延后执行功能：</h4><p>FreeRTOS提供的延后执行功能，基于FreeRTOS提供的 软件定时器模块实现，因此需要使能FreeRTOS的软件定时器功能（软件定时器的使用和相关实现原理可以参考：<a href="https://fengxun2017.github.io/2022/11/16/FreeRTOS-use-timer/">FreeRTOS-使用软件定时器</a>，<a href="https://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/">FreeRTOS-软件定时器实现原理</a>）。并且，还需要在工程配置文件FreeRTOSConfig.h 中添加如下宏定义：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> INCLUDE_xTimerPendFunctionCall	1</span></span><br></pre></td></tr></table></figure>
<br>

<p>实际上，FreeRTOS提供的“延后执行”功能，概念上来说和软件定时器模块并没有关系。但是由于软件定时器模块的实现中存在一个 软件定时器服务任务，该任务从一个软件定时器模块专用消息队列中，获取软件定时器相关的命令，并进行处理。 因此，FreeRTOS直接复用了这一套现成的机制，新增了一个命令<code>EXECUTE_CALLBACK</code>，并让定时器服务任务在收到这个命令时，调用“延后执行”函数。因此，需要延后执行的工作，实际是在软件定时器服务 任务中作为一个回调函数运行的。其整体逻辑如下图所示：</p>
<p><img src="/2022/12/01/FreeRTOS-deferring-work/deferring-schema.png"></p>
<p>其中，可以延后执行的工作，我们放在 deferring_work 函数中执行。<br>中断处理程序中只做必要工作，之后调用API：<code>xTimerPendFunctionCallFromISR</code>函数，将需要延后执行的函数作为参数传入。该API 的内部实现是 将<code>deferring_work函数+EXECUTE_CALLBACK命令</code> 封装成一个消息体，发送到软件定时器模块专用消息队列中。<br>而软件定时器服务任务，会从消息队列中提取消息，判断为<code>EXECUTE_CALLBACK</code>命令后，则执行和命令一起传过来的延后执行函数 <code>deferring_work</code>。</p>
<p>整体过程就是如此。使用的API 具体定义为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xTimerPendFunctionCallFromISR</span><span class="params">( PendedFunction_t xFunctionToPend,</span></span><br><span class="line"><span class="params">                                          <span class="type">void</span> * pvParameter1,</span></span><br><span class="line"><span class="params">                                          <span class="type">uint32_t</span> ulParameter2,</span></span><br><span class="line"><span class="params">                                          BaseType_t * pxHigherPriorityTaskWoken )</span> ;</span><br></pre></td></tr></table></figure>
<ul>
<li><p>xFunctionToPend：即需要延后执行的函数。<br>该函数的原型定义为：<br><code>typedef void (* PendedFunction_t)( void *,                              uint32_t );</code><br>即函数无返回，并且有两个参数。</p>
</li>
<li><p>pvParameter1和ulParameter2： 为自定义使用的参数。<br>这两个参数是和<code>xFunctionToPend</code>函数以及<code>EXECUTE_CALLBACK</code>命令一起发送到消息队列中的，当软件定时器服务任务实际执行<code>xFunctionToPend</code>函数时，会提取这个两个参数，并传给<code>xFunctionToPend</code>函数</p>
</li>
<li><p>pxHigherPriorityTaskWoken：该参数的解释见下文的演示例子。</p>
</li>
</ul>
<p>注意，该函数带有<code>FromISR</code>后缀，表示为中断环境中使用的API。普通线程模式下，也可以使用FreeRTOS提供的延后执行函数，只是使用的是不带<code>FromISR</code>后缀的API：<code>xTimerPendFunctionCall</code></p>
<p>最后，我们以一个具体的例子来演示FreeRTOS“延后执行”功能的使用，简单起见，我们实现一个按键翻转LED灯功能。<br>按键中断处理函数中只做必要的中断源清除，以及按键判断工作，LED翻转则延后执行。</p>
<p>延后执行函数：实现LED翻转</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">deferring_work</span><span class="params">(<span class="type">void</span> *parameter1, <span class="type">uint32_t</span> ulParameter2)</span> &#123;</span><br><span class="line">    </span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;in deferring work\n&quot;</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 根据参数，翻转指定的LED</span></span><br><span class="line">    LED_TOOGLE(ulParameter2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>按键中断处理函数：清除中断源，判断按键，之后将需要调用api 推送需要延后执行的函数。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">GPIOTE_IRQHandler</span><span class="params">(<span class="type">void</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">    BaseType_t higher_task_woken = pdFALSE;</span><br><span class="line">    <span class="keyword">if</span> ( NRF_GPIOTE-&gt;EVENTS_PORT == <span class="number">1</span> )&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//中断处理函数中要清除event,不然会导致一直产生中断</span></span><br><span class="line">        NRF_GPIOTE-&gt;EVENTS_PORT = <span class="number">0</span>;   </span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(IS_BUTTON_PRESSED(BUTTON_1)) &#123;</span><br><span class="line">            <span class="comment">// 这里不需使用pvParameter1，设置为NULL</span></span><br><span class="line">            <span class="comment">// 使用参数ulParameter2，来传递需要翻转哪个LED灯</span></span><br><span class="line">            xTimerPendFunctionCallFromISR(deferring_work, <span class="literal">NULL</span>, LED_1, &amp;higher_task_woken);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    portYIELD_FROM_ISR(higher_task_woken);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上述代码中，在中断处理程序最后使用了<code>portYIELD_FROM_ISR</code>。这是因为在中断处理程序中使用<code>xTimerPendFunctionCallFromISR</code>，实际是向软件定时器模块专用消息队列发送了一个消息（<code>deferring_work函数+EXECUTE_CALLBACK命</code>被封装在一个消息中）。这会让阻塞在该消息队列上的<code>软件定时器服务任务</code>（阻塞中，在等待消息队列有消息）恢复就绪态（有消息了，解除阻塞，恢复就绪态，如果恢复为就绪态的任务优先级比当前任务的优先级更高，则 <strong>higher_task_woken</strong> 会被自动设置为<code>pdTRUE</code>）。如果当前任务（被按键中断打断的任务），其优先级比恢复就绪状态的<code>软件定时器服务任务</code>低，由于我们使用的是抢占式调度的实时操作系统，当存在比当前任务优先级更高的任务就绪时，应该让其立刻被调度，而<code>portYIELD_FROM_ISR</code>的作用就是如果存在更高优先级任务就绪了，就会设置任务切换中断（PendSV中断），这样在中断服务程序<code>GPIOTE_IRQHandler</code>结束后，就会立刻触发任务切换，使得更高优先级的就绪任务被调度运行。</p>
<p>最后的 main函数，我们不创建任何自定义的任务（内核会自动创建一个<code>idle任务</code>，使用软件定时器后，内核也会创建一个 <code>软件定时器服务任务prvTimerTask</code>），直接启动内核调度即可。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;FreeRTOS.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;timers.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;task.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 硬件初始化，使用自己的</span></span><br><span class="line">    bsp_init();</span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 启动内核调度</span></span><br><span class="line">    vTaskStartScheduler();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;something wrong!\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>
ps：需要注意文章代码中的日志输出函数，产品代码中如果需要使用的话，需要考虑线程安全性（多任务安全性），因为中断/任务切换可能发生在另一个任务正在输出日志但还未输出完的时候，这就可能造成日志错乱

<br>
<br>
FreeRTOS交流QQ群-663806972

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/" title="FreeRTOS-延后执行机制">http://fengxun2017.github.io/2022/12/01/FreeRTOS-deferring-work/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/11/27/FreeRTOS-principle_of_timer/" rel="prev" title="FreeRTOS-软件定时器的实现原理">
                  <i class="fa fa-chevron-left"></i> FreeRTOS-软件定时器的实现原理
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/12/08/FreeRTOS-queue-internal-details/" rel="next" title="FreeRTOS-消息队列内部细节">
                  FreeRTOS-消息队列内部细节 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
